const createSlice = ({ name, initialState, reducers }) => {
  const sliceReducers = {
    add: (state, action) => {},
    sub: (state, action) => {},
    'todo/add/fulfilled':  (state, action) => {},
    'todo/add/rejected': (state, action) => {},
    'todo/remove/fulfilled': (state, action) => {},
    'todo/remove/rejected': (state, action) => {}
  };

  //actions 属性值
  const actions = Object.keys(reducers).reduce((acc, actionType) => {
    acc[actionType] = 
    (payload) => ({
      type: actionType,
      payload,
    });
    return acc;
  }, {});
  // {add:(payload) => ({ type: 'add', payload }) ,
  //  sub: payload => ({type: 'sub', payload})}

  //想 sliceReducers 中设置方法 『add, sub』
  Object.keys(reducers).forEach((actionType) => {
    sliceReducers[actionType] = (state, action) => {
      return reducers[actionType](state, action.payload);
    };
  });

  const reducer = (state = initialState, action) => {
    if (sliceReducers[action.type]) {
      return sliceReducers[action.type](state, action);
    }
    return state;
  };

  return {
    name,
    reducer,
    actions: actions,
  };
};


//GPT-4 
const createSlice2 = ({ name, initialState, reducers, extraReducers }) => {
  const actionHandlers = { ...reducers };

  // 如果 extraReducers 是一个函数，则使用 builder pattern
  if (typeof extraReducers === 'function') {
      const builder = {
          addCase: (type, reducer) => {
              actionHandlers[type] = reducer;
          }
      };
      extraReducers(builder);
  } else {
      // 合并额外的 reducers
      Object.assign(actionHandlers, extraReducers);
  }

  return {
      name,
      reducer: (state = initialState, action) => {
          if (actionHandlers[action.type]) {
              return actionHandlers[action.type](state, action);
          }
          return state;
      },
      actions: Object.keys(reducers).reduce((acc, key) => {
          acc[key] = payload => ({ type: `${name}/${key}`, payload });
          return acc;
      }, {})
  };
};
